// pages/merchant/order-management/index.js
const apiService = require('../../../utils/api.js');

Page({
  data: {
    orders: [],
    filteredOrders: [],
    searchKeyword: '',
    currentFilter: 'all',
    showOrderModal: false,
    showRejectModal: false,
    selectedOrder: null,
    rejectReason: '',
    rejectNote: '',
    orderStats: {
      total: 0,
      pendingConfirmation: 0,
      inProgress: 0,
      completed: 0
    }
  },

  onLoad() {
    this.loadOrders();
  },

  onShow() {
    this.loadOrders();
  },

  // 加载订单列表
  async loadOrders() {
    try {
      wx.showLoading({ title: '加载中...' });
      
      // 模拟数据，实际应该调用API
      const mockOrders = [
        {
          orderId: 'ORD202501250001',
          userId: 'user_001',
          userName: '张小明',
          userPhone: '138****1234',
          userAvatar: '/images/default_avatar.png',
          serviceName: '宠物洗浴服务',
          serviceDesc: '中池洗浴 + 烘干',
          appointmentTime: '2025-01-25 14:00',
          storeName: '超级泡泡蓝光店',
          storeAddress: '北京市朝阳区xxx路xxx号',
          storePhone: '010-12345678',
          amount: 88,
          status: 'pending_confirmation',
          statusClass: 'pending_confirmation',
          statusText: '待确认',
          createTime: '2025-01-25 10:30'
        },
        {
          orderId: 'ORD202501250002',
          userId: 'user_002',
          userName: '李小红',
          userPhone: '139****5678',
          userAvatar: '/images/default_avatar.png',
          serviceName: '寄养服务',
          serviceDesc: '温馨单间寄养',
          appointmentTime: '2025-01-25 16:00',
          storeName: '超级泡泡蓝光店',
          storeAddress: '北京市朝阳区xxx路xxx号',
          storePhone: '010-12345678',
          amount: 128,
          status: 'in_progress',
          statusClass: 'in_progress',
          statusText: '进行中',
          createTime: '2025-01-25 11:15'
        },
        {
          orderId: 'ORD202501250003',
          userId: 'user_003',
          userName: '王小强',
          userPhone: '137****9012',
          userAvatar: '/images/default_avatar.png',
          serviceName: '宠物美容服务',
          serviceDesc: '洗浴 + 美容 + 修剪',
          appointmentTime: '2025-01-24 15:30',
          storeName: '超级泡泡蓝光店',
          storeAddress: '北京市朝阳区xxx路xxx号',
          storePhone: '010-12345678',
          amount: 188,
          status: 'completed',
          statusClass: 'completed',
          statusText: '已完成',
          createTime: '2025-01-24 09:45'
        },
        {
          orderId: 'ORD202501250004',
          userId: 'user_004',
          userName: '赵小美',
          userPhone: '136****3456',
          userAvatar: '/images/default_avatar.png',
          serviceName: '宠物洗浴服务',
          serviceDesc: '大池洗浴 + 烘干',
          appointmentTime: '2025-01-25 18:00',
          storeName: '超级泡泡蓝光店',
          storeAddress: '北京市朝阳区xxx路xxx号',
          storePhone: '010-12345678',
          amount: 98,
          status: 'pending_confirmation',
          statusClass: 'pending_confirmation',
          statusText: '待确认',
          createTime: '2025-01-25 12:20'
        }
      ];

      // 计算统计数据
      const stats = {
        total: mockOrders.length,
        pendingConfirmation: mockOrders.filter(o => o.status === 'pending_confirmation').length,
        inProgress: mockOrders.filter(o => o.status === 'in_progress').length,
        completed: mockOrders.filter(o => o.status === 'completed').length
      };

      this.setData({
        orders: mockOrders,
        filteredOrders: mockOrders,
        orderStats: stats
      });

      wx.hideLoading();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      });
      console.error('加载订单失败:', error);
    }
  },

  // 搜索输入
  onSearchInput(e) {
    const keyword = e.detail.value;
    this.setData({ searchKeyword: keyword });
    this.filterOrders();
  },

  // 刷新订单
  onRefreshOrders() {
    this.loadOrders();
  },

  // 筛选条件变化
  onFilterChange(e) {
    const filter = e.currentTarget.dataset.filter;
    this.setData({ currentFilter: filter });
    this.filterOrders();
  },

  // 过滤订单
  filterOrders() {
    const { orders, currentFilter, searchKeyword } = this.data;
    let filtered = orders;

    // 按状态筛选
    if (currentFilter !== 'all') {
      filtered = filtered.filter(order => order.status === currentFilter);
    }

    // 按关键词搜索
    if (searchKeyword) {
      filtered = filtered.filter(order => 
        order.orderId.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        order.userName.toLowerCase().includes(searchKeyword.toLowerCase()) ||
        order.userPhone.includes(searchKeyword)
      );
    }

    this.setData({ filteredOrders: filtered });
  },

  // 确认订单
  async onConfirmOrder(e) {
    const order = e.currentTarget.dataset.order;
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新订单状态
      const { orders } = this.data;
      const updatedOrders = orders.map(o => 
        o.orderId === order.orderId ? { 
          ...o, 
          status: 'in_progress', 
          statusClass: 'in_progress', 
          statusText: '进行中' 
        } : o
      );
      
      // 重新计算统计数据
      const stats = {
        total: updatedOrders.length,
        pendingConfirmation: updatedOrders.filter(o => o.status === 'pending_confirmation').length,
        inProgress: updatedOrders.filter(o => o.status === 'in_progress').length,
        completed: updatedOrders.filter(o => o.status === 'completed').length
      };
      
      this.setData({ 
        orders: updatedOrders,
        orderStats: stats
      });
      this.filterOrders();
      
      wx.hideLoading();
      wx.showToast({
        title: '订单确认成功',
        icon: 'success'
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '确认失败',
        icon: 'error'
      });
      console.error('确认订单失败:', error);
    }
  },

  // 拒绝订单
  onRejectOrder(e) {
    const order = e.currentTarget.dataset.order;
    this.setData({
      showRejectModal: true,
      selectedOrder: order,
      rejectReason: '',
      rejectNote: ''
    });
  },

  // 选择拒绝原因
  onSelectRejectReason(e) {
    const reason = e.currentTarget.dataset.reason;
    this.setData({ rejectReason: reason });
  },

  // 拒绝说明输入
  onRejectNoteInput(e) {
    this.setData({ rejectNote: e.detail.value });
  },

  // 确认拒绝
  async onConfirmReject() {
    const { selectedOrder, rejectReason, rejectNote } = this.data;
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新订单状态
      const { orders } = this.data;
      const updatedOrders = orders.map(o => 
        o.orderId === selectedOrder.orderId ? { 
          ...o, 
          status: 'cancelled', 
          statusClass: 'cancelled', 
          statusText: '已取消',
          rejectReason,
          rejectNote
        } : o
      );
      
      // 重新计算统计数据
      const stats = {
        total: updatedOrders.length,
        pendingConfirmation: updatedOrders.filter(o => o.status === 'pending_confirmation').length,
        inProgress: updatedOrders.filter(o => o.status === 'in_progress').length,
        completed: updatedOrders.filter(o => o.status === 'completed').length
      };
      
      this.setData({ 
        orders: updatedOrders,
        orderStats: stats
      });
      this.filterOrders();
      
      wx.hideLoading();
      wx.showToast({
        title: '订单已拒绝',
        icon: 'success'
      });
      
      this.onCloseRejectModal();
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '拒绝失败',
        icon: 'error'
      });
      console.error('拒绝订单失败:', error);
    }
  },

  // 完成订单
  async onCompleteOrder(e) {
    const order = e.currentTarget.dataset.order;
    
    try {
      wx.showLoading({ title: '处理中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 更新订单状态
      const { orders } = this.data;
      const updatedOrders = orders.map(o => 
        o.orderId === order.orderId ? { 
          ...o, 
          status: 'completed', 
          statusClass: 'completed', 
          statusText: '已完成' 
        } : o
      );
      
      // 重新计算统计数据
      const stats = {
        total: updatedOrders.length,
        pendingConfirmation: updatedOrders.filter(o => o.status === 'pending_confirmation').length,
        inProgress: updatedOrders.filter(o => o.status === 'in_progress').length,
        completed: updatedOrders.filter(o => o.status === 'completed').length
      };
      
      this.setData({ 
        orders: updatedOrders,
        orderStats: stats
      });
      this.filterOrders();
      
      wx.hideLoading();
      wx.showToast({
        title: '订单完成',
        icon: 'success'
      });
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '完成失败',
        icon: 'error'
      });
      console.error('完成订单失败:', error);
    }
  },

  // 取消订单
  async onCancelOrder(e) {
    const order = e.currentTarget.dataset.order;
    
    wx.showModal({
      title: '确认取消',
      content: `确定要取消订单"${order.orderId}"吗？`,
      success: async (res) => {
        if (res.confirm) {
          try {
            wx.showLoading({ title: '处理中...' });
            
            // 模拟API调用
            await new Promise(resolve => setTimeout(resolve, 1000));
            
            // 更新订单状态
            const { orders } = this.data;
            const updatedOrders = orders.map(o => 
              o.orderId === order.orderId ? { 
                ...o, 
                status: 'cancelled', 
                statusClass: 'cancelled', 
                statusText: '已取消' 
              } : o
            );
            
            // 重新计算统计数据
            const stats = {
              total: updatedOrders.length,
              pendingConfirmation: updatedOrders.filter(o => o.status === 'pending_confirmation').length,
              inProgress: updatedOrders.filter(o => o.status === 'in_progress').length,
              completed: updatedOrders.filter(o => o.status === 'completed').length
            };
            
            this.setData({ 
              orders: updatedOrders,
              orderStats: stats
            });
            this.filterOrders();
            
            wx.hideLoading();
            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            });
          } catch (error) {
            wx.hideLoading();
            wx.showToast({
              title: '取消失败',
              icon: 'error'
            });
            console.error('取消订单失败:', error);
          }
        }
      }
    });
  },

  // 联系用户
  onContactUser(e) {
    const order = e.currentTarget.dataset.order;
    
    wx.showModal({
      title: '联系用户',
      content: `是否要联系用户"${order.userName}"？\n电话：${order.userPhone}`,
      confirmText: '拨打电话',
      success: (res) => {
        if (res.confirm) {
          wx.makePhoneCall({
            phoneNumber: order.userPhone.replace(/\*/g, ''),
            fail: () => {
              wx.showToast({
                title: '拨号失败',
                icon: 'error'
              });
            }
          });
        }
      }
    });
  },

  // 查看订单详情
  onViewOrderDetail(e) {
    const order = e.currentTarget.dataset.order;
    this.setData({
      showOrderModal: true,
      selectedOrder: order
    });
  },

  // 从弹窗联系用户
  onContactUserFromModal() {
    const { selectedOrder } = this.data;
    this.onContactUser({ currentTarget: { dataset: { order: selectedOrder } } });
  },

  // 关闭订单详情弹窗
  onCloseOrderModal() {
    this.setData({
      showOrderModal: false,
      selectedOrder: null
    });
  },

  // 关闭拒绝订单弹窗
  onCloseRejectModal() {
    this.setData({
      showRejectModal: false,
      selectedOrder: null,
      rejectReason: '',
      rejectNote: ''
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  }
});